package com.cskaoyan.market.service.admin.impl;

import com.cskaoyan.market.db.domain.*;
import com.cskaoyan.market.db.mapper.MarketAdminMapper;
import com.cskaoyan.market.db.mapper.MarketPermissionMapper;
import com.cskaoyan.market.db.mapper.MarketRoleMapper;
import com.cskaoyan.market.service.admin.MarketAuthService;
import com.cskaoyan.market.util.admin.Permission;
import com.cskaoyan.market.util.admin.PermissionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @ClassName MarketAdminServiceImpl
 * @Description: TODO
 * @Author 远志 zhangsong@cskaoyan.onaliyun.com
 * @Date 2023/5/5 11:08
 * @Version V1.0
 **/
@Service
public class MarketAuthServiceImpl implements MarketAuthService {

    private static final String YOUR_PACKAGE_NAME = "com.cskaoyan.market.controller.admin";

    @Autowired
    private ApplicationContext context;
    @Autowired
    MarketAdminMapper adminMapper;
    @Autowired
    MarketRoleMapper roleMapper;
    @Autowired
    MarketPermissionMapper permissionMapper;

    //    绝对不能将 SqlSession 实例的引用放在一个类的静态域，甚至一个类的实例变量也不行。 也绝不能将 SqlSession 实例的引用放在任何类型的托管作用域中，比如 Servlet 框架中的 HttpSession。
    //SqlSession sqlSession;
    @Override
    public List<MarketAdmin> login(String username, String password) {

        //当我们执行当前对象的方法时，那么执行的便是对应的sql语句
        MarketAdminExample marketAdminExample = new MarketAdminExample();
        //select * from market_admin where username = and password =
        marketAdminExample.or().andUsernameEqualTo(username).andPasswordEqualTo(password);
        List<MarketAdmin> marketAdmins = adminMapper.selectByExample(marketAdminExample);

        return marketAdmins;
    }

    @Override
    public Map<String, Object> info(MarketAdmin admin, Integer[] roleIds) {
        Map<String, Object> result = new HashMap<>();

        List<String> roles = new ArrayList<>();
        for (Integer roleId : roleIds) {
            MarketRole marketRole = roleMapper.selectByPrimaryKey(roleId);
            roles.add(marketRole.getName());
        }
        result.put("roles", roles);
        result.put("name", admin.getUsername());

        Set<String> perms = new HashSet<>();

        for (Integer roleId : roleIds) {
            if (roleId == 1){
                perms.add("*");
            }else {
                perms = getPerms(roleId);
            }
        }

        result.put("perms", perms);

        result.put("avatar", admin.getAvatar());

        return result;
    }

    @Override
    public String checkPasswordByUsername(String username) {
        MarketAdminExample adminExample = new MarketAdminExample();
        adminExample.or().andUsernameEqualTo(username);
        MarketAdmin admin = adminMapper.selectOneByExample(adminExample);
        return admin.getPassword();
    }

    @Override
    public MarketAdmin getAdminByUsername(String username, String password) {
        MarketAdminExample adminExample = new MarketAdminExample();
        adminExample.or().andDeletedEqualTo(false).andUsernameEqualTo(username).andPasswordEqualTo(password);
        MarketAdmin admin = adminMapper.selectOneByExample(adminExample);

        return admin;
    }

    private Set<String> getPerms(Integer roleId) {
        Set<String> result = new HashSet<>();
        MarketPermissionExample permissionExample = new MarketPermissionExample();
        permissionExample.or().andDeletedEqualTo(false).andRoleIdEqualTo(roleId);
        List<MarketPermission> permissionList = permissionMapper.selectByExample(permissionExample);

        List<String> rolePermissions = new ArrayList<>();
        for (MarketPermission permission : permissionList) {

            String s = permission.getPermission();
            String replaceAll = s.replaceAll(":", "/");
            rolePermissions.add(replaceAll);
        }

        String basicPackage = YOUR_PACKAGE_NAME;
        List<Permission> permissions = PermissionUtil.listPermission(context, basicPackage);

        for (Permission permission : permissions) {
            // "POST /admin/category/delete",
            String api = permission.getApi();
            for (String rolePermission : rolePermissions) {
                // admin/category/delete
                if (api.endsWith(rolePermission)){
                    result.add(api);
                }
            }
        }
        return result;
    }
}
